<?php
/**
 * 辅助工具与资源组件
 * 提供系统诊断、使用指南、费用计算和服务状态查询等自助工具
 * 帮助用户快速解决常见问题，获取所需资源
 */

// 组件配置键名
$configKey = 'support_helper';

// 文本配置
$texts = [
    'related_resources_title' => '相关资源',
    'tool_details_title' => '工具详情',
    'close_button' => '关闭',
    'diagnostic_submit_button' => '提交诊断请求',
    'diagnostic_description' => '请提供以下信息，我们将为您分析可能的解决方案。',
    'calculator_title' => '费用计算器',
    'calculator_description' => '根据您的需求，估算使用我们服务的费用。',
    'calculator_result_title' => '估算结果',
    'calculator_result_description' => '每月预估费用（按所选参数计算）',
    'status_history_title' => '历史状态',
    'status_history_link' => '查看过去30天的服务状态记录',
    'status_operational' => '正常运行',
    'status_degraded' => '性能下降',
    'status_outage' => '服务中断',
    'file_type_pdf' => 'PDF',
    'file_type_video' => '视频',
    'status_description' => '实时查看我们各系统服务的当前运行状态。',
    'guide_description' => '浏览我们的资源库，找到您需要的帮助文档和教程。'
];

// 默认配置
$defaultConfig = [
    'section_id' => 'support-helper',
    'section_pretitle' => '辅助工具',
    'section_title' => '自助工具与资源',
    'section_subtitle' => '使用这些实用工具快速解决常见问题，获取所需资源',
    'bg_color' => 'gray-50',
    'card_style' => 'modern', // modern, classic, minimal
    'tools' => [
        [
            'id' => 'diagnostic',
            'title' => '系统诊断工具',
            'description' => '自动检测常见问题，提供解决方案',
            'icon' => 'fa-stethoscope',
            'accent_color' => 'blue-500',
            'action_text' => '开始诊断',
            'form_fields' => [
                [
                    'name' => 'issue_type',
                    'label' => '问题类型',
                    'type' => 'select',
                    'options' => [
                        '' => '请选择问题类型',
                        'login' => '登录问题',
                        'performance' => '性能问题',
                        'feature' => '功能异常',
                        'payment' => '支付问题',
                        'other' => '其他问题'
                    ]
                ],
                [
                    'name' => 'description',
                    'label' => '问题描述',
                    'type' => 'textarea',
                    'placeholder' => '请简要描述您遇到的问题...'
                ]
            ]
        ],
        [
            'id' => 'guide',
            'title' => '使用指南查询',
            'description' => '搜索相关教程和使用手册',
            'icon' => 'fa-book',
            'accent_color' => 'green-500',
            'action_text' => '浏览指南',
            'resources' => [
                '新手入门' => [
                    'getting-started.pdf',
                    'account-setup.html',
                    'basic-features.mp4'
                ],
                '高级功能' => [
                    'advanced-settings.pdf',
                    'workflow-automation.html',
                    'integration-guide.pdf'
                ],
                '常见问题' => [
                    'troubleshooting.pdf',
                    'error-codes.html',
                    'faq-video-series.mp4'
                ]
            ]
        ],
        [
            'id' => 'calculator',
            'title' => '费用计算器',
            'description' => '估算服务使用成本和潜在节省',
            'icon' => 'fa-calculator',
            'accent_color' => 'purple-500',
            'action_text' => '开始计算',
            'calculator_fields' => [
                [
                    'name' => 'users',
                    'label' => '用户数量',
                    'type' => 'number',
                    'min' => 1,
                    'max' => 1000,
                    'default' => 10
                ],
                [
                    'name' => 'plan',
                    'label' => '套餐类型',
                    'type' => 'select',
                    'options' => [
                        'basic' => '基础版',
                        'professional' => '专业版',
                        'enterprise' => '企业版'
                    ]
                ],
                [
                    'name' => 'duration',
                    'label' => '使用时长(月)',
                    'type' => 'range',
                    'min' => 1,
                    'max' => 36,
                    'default' => 12
                ]
            ]
        ],
        [
            'id' => 'status',
            'title' => '服务状态查询',
            'description' => '查看系统各功能模块的当前状态',
            'icon' => 'fa-server',
            'accent_color' => 'orange-500',
            'action_text' => '查看状态',
            'services' => [
                [
                    'name' => '主系统',
                    'status' => 'operational', // operational, degraded, outage
                    'last_updated' => '2分钟前'
                ],
                [
                    'name' => '支付系统',
                    'status' => 'operational',
                    'last_updated' => '15分钟前'
                ],
                [
                    'name' => '移动端服务',
                    'status' => 'degraded',
                    'last_updated' => '1小时前',
                    'message' => '部分用户可能遇到推送延迟问题'
                ],
                [
                    'name' => 'API服务',
                    'status' => 'operational',
                    'last_updated' => '30分钟前'
                ]
            ]
        ]
    ],
    'related_resources' => [
        [
            'title' => '社区论坛',
            'description' => '与其他用户交流经验和解决方案',
            'icon' => 'fa-comments',
            'link' => '/community'
        ],
        [
            'title' => '视频教程',
            'description' => '观看详细的功能使用演示',
            'icon' => 'fa-video-camera',
            'link' => '/tutorials'
        ],
        [
            'title' => '开发者文档',
            'description' => 'API和集成相关技术文档',
            'icon' => 'fa-code',
            'link' => '/developers'
        ]
    ],
    'texts' => $texts
];

// 获取传入配置
$customConfig = $pageConfig['components'][$configKey] ?? [];

// 合并配置
$data = array_merge($defaultConfig, $customConfig);

// 处理背景样式
$bgClass = "bg-{$data['bg_color']}";

// 处理卡片样式
$cardBaseClasses = "p-6 rounded-xl transition-all duration-300 h-full";
$cardStyles = [
    'modern' => $cardBaseClasses . " bg-white shadow-md hover:shadow-lg hover:-translate-y-1",
    'classic' => $cardBaseClasses . " bg-white border border-gray-200 hover:border-primary",
    'minimal' => $cardBaseClasses . " bg-transparent hover:bg-white/50"
];
$cardClass = $cardStyles[$data['card_style']] ?? $cardStyles['modern'];

// 确定当前激活的工具
$activeTool = $_GET['tool'] ?? '';
?>

<!-- 支持辅助工具区域 -->
<section id="<?= htmlspecialchars($data['section_id']); ?>" class="py-16">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <!-- 区域标题 -->
        <div class="text-center max-w-3xl mx-auto mb-16">
            <?php if (!empty($data['section_pretitle'])): ?>
                <span class="inline-block text-sm font-semibold text-blue-600 uppercase tracking-wider mb-2">
                    <?= htmlspecialchars($data['section_pretitle']); ?>
                </span>
            <?php endif; ?>
            
            <h2 class="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
                <?= htmlspecialchars($data['section_title']); ?>
            </h2>
            
            <?php if (!empty($data['section_subtitle'])): ?>
                <p class="text-lg text-gray-600">
                    <?= htmlspecialchars($data['section_subtitle']); ?>
                </p>
            <?php endif; ?>
        </div>

        <!-- 工具卡片网格 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8 mb-16">
            <?php foreach ($data['tools'] as $tool): ?>
                <div class="<?= $cardClass; ?> group" data-tool-card>
                    <!-- 图标容器 -->
                    <div class="w-14 h-14 bg-<?= $tool['accent_color']; ?>/10 text-<?= $tool['accent_color']; ?> rounded-lg flex items-center justify-center mb-6 text-2xl transition-transform duration-500 group-hover:scale-110">
                        <i class="fa <?= htmlspecialchars($tool['icon']); ?>"></i>
                    </div>
                    
                    <!-- 工具信息 -->
                    <h3 class="text-xl font-semibold mb-3 text-gray-900 transition-colors duration-300 group-hover:text-<?= $tool['accent_color']; ?>">
                        <?= htmlspecialchars($tool['title']); ?>
                    </h3>
                    
                    <p class="text-gray-600 mb-6 flex-grow">
                        <?= htmlspecialchars($tool['description']); ?>
                    </p>
                    
                    <!-- 操作按钮 -->
                    <button 
                        class="tool-action w-full py-3 px-4 bg-<?= $tool['accent_color']; ?>/10 text-<?= $tool['accent_color']; ?> font-medium rounded-lg transition-all duration-300 hover:bg-<?= $tool['accent_color']; ?> hover:text-white flex items-center justify-center"
                        data-tool="<?= $tool['id']; ?>"
                    >
                        <span><?= htmlspecialchars($tool['action_text']); ?></span>
                        <i class="fa fa-arrow-right ml-2 transition-transform duration-300 group-hover:translate-x-1"></i>
                    </button>
                </div>
            <?php endforeach; ?>
        </div>
        
        <!-- 工具详情区域 -->
        <div id="tool-details" class="max-w-4xl mx-auto <?= empty($activeTool) ? 'hidden' : ''; ?>">
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <!-- 详情头部 -->
        <div class="p-6 border-b border-gray-100 flex justify-between items-center">
            <h3 class="text-2xl font-bold text-gray-900" id="detail-title"><?= htmlspecialchars($data['texts']['tool_details_title']); ?></h3>
            <button id="close-detail" class="text-gray-500 hover:text-gray-700 transition-colors">
                <i class="fa fa-times text-xl"></i> <?= htmlspecialchars($data['texts']['close_button']); ?>
            </button>
        </div>
                
                <!-- 详情内容 -->
                <div class="p-6" id="detail-content">
                    <!-- 工具内容将通过JS动态加载 -->
                </div>
            </div>
        </div>
        
        <!-- 相关资源 -->
        <div class="max-w-4xl mx-auto mt-16">
            <h3 class="text-2xl font-bold text-center mb-10 text-gray-900"><?= htmlspecialchars($data['texts']['related_resources_title']); ?></h3>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <?php foreach ($data['related_resources'] as $resource): ?>
                    <a href="<?= htmlspecialchars($resource['link']); ?>" class="block p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300 border border-gray-100">
                        <div class="w-12 h-12 bg-blue-100 text-blue-600 rounded-lg flex items-center justify-center mb-4 text-xl">
                            <i class="fa <?= htmlspecialchars($resource['icon']); ?>"></i>
                        </div>
                        <h4 class="text-lg font-semibold mb-2 text-gray-900 hover:text-blue-600 transition-colors">
                            <?= htmlspecialchars($resource['title']); ?>
                        </h4>
                        <p class="text-gray-600 text-sm">
                            <?= htmlspecialchars($resource['description']); ?>
                        </p>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</section>

<!-- 辅助工具交互脚本 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 工具数据
    const toolsData = <?php echo json_encode($data['tools']); ?>;
    const textsData = <?php echo json_encode($data['texts']); ?>;
    let activeTool = '<?php echo $activeTool; ?>';
    
    // 工具卡片动画
    const toolCards = document.querySelectorAll('[data-tool-card]');
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1 });
    
    toolCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(30px)';
        card.style.transition = `opacity 0.5s ease ${index * 0.1}s, transform 0.5s ease ${index * 0.1}s`;
        observer.observe(card);
    });
    
    // 打开工具详情
    document.querySelectorAll('.tool-action').forEach(button => {
        button.addEventListener('click', function() {
            const toolId = this.getAttribute('data-tool');
            openToolDetail(toolId);
        });
    });
    
    // 关闭工具详情
    document.getElementById('close-detail').addEventListener('click', function() {
        closeToolDetail();
    });
    
    // 打开工具详情函数
    function openToolDetail(toolId) {
        const tool = toolsData.find(t => t.id === toolId);
        if (!tool) return;
        
        // 更新URL
        const url = new URL(window.location);
        url.searchParams.set('tool', toolId);
        window.history.pushState({}, '', url);
        
        // 更新标题
        document.getElementById('detail-title').textContent = tool.title;
        
        // 根据工具类型生成内容
        let contentHtml = '';
        
        // 系统诊断工具
        if (toolId === 'diagnostic') {
            contentHtml = `
                <p class="text-gray-600 mb-6">${tool.description}${textsData.diagnostic_description}</p>
                <form id="diagnostic-form" class="space-y-6">
                    ${tool.form_fields.map(field => `
                        <div class="form-group">
                            <label for="${field.name}" class="block text-gray-700 font-medium mb-2">
                                ${field.label}
                            </label>
                            ${field.type === 'select' ? `
                                <select id="${field.name}" name="${field.name}" class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-${tool.accent_color} focus:border-transparent">
                                    ${Object.entries(field.options).map(([value, label]) => `
                                        <option value="${value}">${label}</option>
                                    `).join('')}
                                </select>
                            ` : field.type === 'textarea' ? `
                                <textarea id="${field.name}" name="${field.name}" rows="4" placeholder="${field.placeholder}" class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-${tool.accent_color} focus:border-transparent"></textarea>
                            ` : `
                                <input type="${field.type}" id="${field.name}" name="${field.name}" class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-${tool.accent_color} focus:border-transparent">
                            `}
                        </div>
                    `).join('')}
                    <button type="submit" class="w-full py-3 px-4 bg-${tool.accent_color} hover:bg-${tool.accent_color}/90 text-white font-medium rounded-lg transition-all duration-300">
                        ${textsData.diagnostic_submit_button}
                    </button>
                </form>
            `;
        }
        
        // 使用指南查询
        else if (toolId === 'guide') {
            contentHtml = `
                <p class="text-gray-600 mb-6">${textsData.guide_description}</p>
                <div class="space-y-6">
                    ${Object.entries(tool.resources).map(([category, items]) => `
                        <div>
                            <h4 class="text-lg font-semibold mb-3 text-gray-900">${category}</h4>
                            <ul class="space-y-2">
                                ${items.map(item => {
                                    const isPdf = item.endsWith('.pdf');
                                    const isVideo = item.endsWith('.mp4');
                                    const isHtml = item.endsWith('.html');
                                    const icon = isPdf ? 'fa-file-pdf-o' : isVideo ? 'fa-file-video-o' : 'fa-file-text-o';
                                    return `
                                        <li>
                                            <a href="/guides/${item}" class="flex items-center text-blue-600 hover:text-blue-800 hover:underline">
                                                <i class="fa ${icon} mr-2"></i>
                                                <span>${item.split('.').slice(0, -1).join('.')}</span>
                                                ${isPdf ? `<span class="ml-2 text-xs bg-red-100 text-red-800 px-2 py-0.5 rounded">${textsData.file_type_pdf}</span>` : ''}
                                                ${isVideo ? `<span class="ml-2 text-xs bg-purple-100 text-purple-800 px-2 py-0.5 rounded">${textsData.file_type_video}</span>` : ''}
                                            </a>
                                        </li>
                                    `;
                                }).join('')}
                            </ul>
                        </div>
                    `).join('')}
                </div>
            `;
        }
        
        // 费用计算器
        else if (toolId === 'calculator') {
            contentHtml = `
                <p class="text-gray-600 mb-6">${textsData.calculator_description}</p>
                <div class="space-y-6">
                    <form id="cost-calculator" class="space-y-6">
                        ${tool.calculator_fields.map(field => `
                            <div class="form-group">
                                <label for="${field.name}" class="block text-gray-700 font-medium mb-2">
                                    ${field.label}
                                    ${field.type === 'range' ? `<span id="${field.name}-value" class="ml-2 text-${tool.accent_color} font-semibold">${field.default}</span>` : ''}
                                </label>
                                ${field.type === 'range' ? `
                                    <input type="${field.type}" id="${field.name}" name="${field.name}" 
                                        min="${field.min}" max="${field.max}" value="${field.default}"
                                        class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-${tool.accent_color}">
                                ` : field.type === 'select' ? `
                                    <select id="${field.name}" name="${field.name}" class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-${tool.accent_color} focus:border-transparent">
                                        ${Object.entries(field.options).map(([value, label]) => `
                                            <option value="${value}">${label}</option>
                                        `).join('')}
                                    </select>
                                ` : `
                                    <input type="${field.type}" id="${field.name}" name="${field.name}" 
                                        min="${field.min}" max="${field.max}" value="${field.default}"
                                        class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-${tool.accent_color} focus:border-transparent">
                                `}
                            </div>
                        `).join('')}
                    </form>
                    
                    <!-- 计算结果 -->
                    <div class="p-6 bg-gray-50 rounded-lg border border-gray-100">
                        <h4 class="text-lg font-semibold mb-3 text-gray-900">${textsData.calculator_result_title}</h4>
                        <div class="text-3xl font-bold text-${tool.accent_color}" id="calculator-result">¥0.00</div>
                        <p class="text-gray-600 mt-2">${textsData.calculator_result_description}</p>
                    </div>
                </div>
            `;
        }
        
        // 服务状态查询
        else if (toolId === 'status') {
            contentHtml = `
                <p class="text-gray-600 mb-6">${textsData.status_description}</p>
                <div class="space-y-4">
                    ${tool.services.map(service => `
                        <div class="p-4 rounded-lg border ${
                            service.status === 'operational' ? 'border-green-200 bg-green-50' :
                            service.status === 'degraded' ? 'border-yellow-200 bg-yellow-50' :
                            'border-red-200 bg-red-50'
                        }">
                            <div class="flex justify-between items-start">
                                <div>
                                    <h4 class="font-semibold text-gray-900">${service.name}</h4>
                                    <div class="flex items-center mt-1">
                                        <span class="w-3 h-3 rounded-full mr-2 ${service.status === 'operational' ? 'bg-green-500' : service.status === 'degraded' ? 'bg-yellow-500' : 'bg-red-500'}"></span>
                                        <span class="text-sm ${service.status === 'operational' ? 'text-green-800' : service.status === 'degraded' ? 'text-yellow-800' : 'text-red-800'}">
                                            ${service.status === 'operational' ? textsData.status_operational :
                                              service.status === 'degraded' ? textsData.status_degraded :
                                              textsData.status_outage}
                                        </span>
                                    </div>
                                </div>
                                <span class="text-xs text-gray-500">${service.last_updated}</span>
                            </div>
                            ${service.message ? `<p class="mt-3 text-sm text-gray-700">${service.message}</p>` : ''}
                        </div>
                    `).join('')}
                </div>
                <div class="mt-6 pt-6 border-t border-gray-100">
                    <h4 class="font-semibold text-gray-900 mb-2">${textsData.status_history_title}</h4>
                    <a href="/status-history" class="text-blue-600 hover:text-blue-800 hover:underline text-sm">
                        ${textsData.status_history_link} <i class="fa fa-angle-right ml-1"></i>
                    </a>
                </div>
            `;
        }
        
        // 更新内容
        document.getElementById('detail-content').innerHTML = contentHtml;
        document.getElementById('tool-details').classList.remove('hidden');
        
        // 初始化特定工具的交互
        if (toolId === 'calculator') {
            initCalculator();
        } else if (toolId === 'diagnostic') {
            initDiagnosticForm();
        }
        
        // 滚动到详情区域
        document.getElementById('tool-details').scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
    
    // 关闭工具详情函数
    function closeToolDetail() {
        // 更新URL
        const url = new URL(window.location);
        url.searchParams.delete('tool');
        window.history.pushState({}, '', url);
        
        document.getElementById('tool-details').classList.add('hidden');
    }
    
    // 初始化计算器
    function initCalculator() {
        const durationSlider = document.getElementById('duration');
        const durationValue = document.getElementById('duration-value');
        const usersInput = document.getElementById('users');
        const planSelect = document.getElementById('plan');
        const resultDisplay = document.getElementById('calculator-result');
        
        // 计算费用的函数
        function calculateCost() {
            const users = parseInt(usersInput.value) || 10;
            const plan = planSelect.value || 'basic';
            // const duration = parseInt(durationSlider.value) || 12;
            
            // 基础价格（示例）
            const basePrices = {
                basic: 99,
                professional: 199,
                enterprise: 499
            };
            
            // 计算单价（用户数折扣）
            let pricePerUser = basePrices[plan];
            if (users > 50) pricePerUser *= 0.9;
            if (users > 200) pricePerUser *= 0.8;
            if (users > 500) pricePerUser *= 0.7;
            
            // 计算总价
            const total = users * pricePerUser;
            
            // 更新显示
            resultDisplay.textContent = `¥${total.toFixed(2)}`;
        }
        
        // 监听输入变化
        durationSlider.addEventListener('input', function() {
            durationValue.textContent = this.value;
            calculateCost();
        });
        
        usersInput.addEventListener('input', calculateCost);
        planSelect.addEventListener('change', calculateCost);
        
        // 初始计算
        calculateCost();
    }
    
    // 初始化诊断表单
    function initDiagnosticForm() {
        const form = document.getElementById('diagnostic-form');
        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                alert('诊断请求已提交，我们将为您分析可能的解决方案并尽快回复。');
                closeToolDetail();
            });
        }
    }
    
    // 初始加载时打开指定工具
    if (activeTool) {
        openToolDetail(activeTool);
    }
});
</script>
    